/**
 * @description 创建订单
 * @author unhejing (成都-敬宇杰)
 * @date 2020-02-26 上午11:28:02
 */

/**
 * 入参数
{
	"remark":"订单备注",
	"pay_type":0,// 支付方式 0 现金支付 1 微信支付
	"productItemList": [
		{
			"product_id": "238",
			"num": 1
		},
		{
			"product_id": "239",
			"num": 1
		}
	]
}
 * 保存的参数
"data": {
	"_id": "253",
	"address": "2单元9-7",
	"amount_payable": 344.52,
	"consignee_name": "马云",
	"create_time": 1582167318905,
	"link_phone": "17695479404",
	"order_code": "HTZ2019091010003",
	"pay_type": "现金支付",
	"productItemList": [
		{
			"_id": "238",
			"book_price": 78,
			"create_time": 1582168708534,
			"num": 1,
			"order_code": "HTZ2019091010003",
			"primary_img": "https://img13.360buyimg.com/n0/jfs/t1/2105/20/5696/216613/5ba094f4E02210af7/9a61e11b623c5cfc.jpg",
			"product_code": "100000384344",
			"product_id": "00061b1a-6e79-4bc4-b491-3a500f526afc",
			"product_name": "金克里特 特级初榨橄榄油1000ml",
			"sale_unit": "瓶",
			"sum_price": 78
		},
		{
			"_id": "239",
			"book_price": 59.4,
			"create_time": 1582168708534,
			"num": 3,
			"order_code": "HTZ2019091010003",
			"primary_img": "https://img13.360buyimg.com/n0/jfs/t8806/193/753910013/512578/b473c342/59ae65edN87264964.jpg",
			"product_code": "4485343",
			"product_id": "fa8879fc-e3d7-45bb-888f-ac02453d047c",
			"product_name": "和茶原叶 茶叶 花果茶 白桃乌龙茶 调味茶 三角袋泡茶 冷泡茶包 48g",
			"sale_unit": "盒",
			"sum_price": 178.2
		},
		{
			"_id": "240",
			"book_price": 58.32,
			"create_time": 1582168708534,
			"num": 1,
			"order_code": "HTZ2019091010003",
			"primary_img": "http://img13.360buyimg.com/n0/jfs/t8347/104/778706312/519515/a0e2af46/59ae644cN1c58e0be.jpg",
			"product_code": "4485369",
			"product_id": "66a11726-35ab-4ae7-b84c-49136d2d0547",
			"product_name": "和茶原叶 茶叶 花草茶 玫瑰荷叶茶 调味茶 三角袋泡茶包 64g",
			"sale_unit": "盒",
			"sum_price": 58.32
		}
	],
	"real_pay": 344.52,
	"remark": "请下午配送",
	"status": 0,
	"statusDesc": "待付款",
	"update_time": 1582167318905,
	"user_id": "1"
}
 */
const {
	validateToken
} = require('../../utils/validateToken.js')
'use strict';
const db = uniCloud.database()
exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('event:' + event)
	let tokenRes = await validateToken(event.token)
	if (tokenRes.code != 0) {
		return tokenRes;
	}
	event.user_id = tokenRes.user_id;
	/**
	 * ******************测试的时候打开该注释start******************
	 */
	// event.user_id = "1";
	// event.remark = "接口测试订单";
	// event.pay_type = 1;
	// event.productItemList = [
	// 		{
	// 			product_id: "007abbbe-11ba-438e-a4e7-2441085784d8",
	// 			num: 1
	// 		},
	// 		{
	// 			product_id: "00f294fb-b972-4271-8bb0-f21292792977",
	// 			num: 2
	// 		}
	// ]
	
	// let addUserInfo = {
	//     guid: "2008017YR51G1XWH",
	//     wx_open_id: "oRrdQt8RirlYXoH60J-2tO39Xhpc",
	//     name: "unhejing",
	//     phone: "17695479404",
	// 	address:"2单元1-1",
	//     photo: "https://unhejing-img.oss-cn-beijing.aliyuncs.com/UTOOLS1581511281662.jpg",
	//     create_time: 1582120959821, // 时间戳 GMT
	//     create_ip: "125.68.18.43" // 注册 ip
	// }
	// let userRes = await db.collection('user').doc(event.user_id).update(addUserInfo);
	// console.log("添加用户信息："+JSON.stringify(userRes))
	/**
	 * ******************测试的时候打开该注释end******************
	 */
	
	if (event.user_id == '' || !event.user_id) {
		return {
			success: false,
			code: -1,
			msg: '参数错误，缺少用户id'
		}
	}
	var randomNum = "";
	for (var i = 0; i < 4; i++) {
		randomNum += Math.floor(Math.random() * 10)
	}
	// 查询用户信息
	let userData = await db.collection('user').doc(event.user_id).get();
	if (!userData.data || userData.data.length === 0) {
		return {
			success: false,
			code: -1,
			msg: '查询用户信息出错'
		}
	}
	let userInfo = userData.data[0];
	if(!userInfo.phone || userInfo.phone == ''){
		return {
			success: false,
			code: -1,
			msg: '请设置联系电话'
		}
	}
	if(!userInfo.address || userInfo.address == ''){
		return {
			success: false,
			code: -1,
			msg: '请设置收货地址'
		}
	}
	if(!userInfo.name || userInfo.name == ''){
		return {
			success: false,
			code: -1,
			msg: '请设置收货收货人姓名'
		}
	}
	console.log("下单用户信息："+JSON.stringify(userInfo))

	// 构建订单对象
	let currentTime = new Date().getTime();
	let orderCode = "SQDG" + currentTime + randomNum;
	let orderObj = {
		order_code: orderCode,
		user_id: event.user_id,
		link_phone: userInfo.phone,
		address: userInfo.address,
		consignee_name: userInfo.name,
		amount_payable: 0,
		real_pay: 0,
		status: 0,
		remark: event.remark,
		create_time: currentTime,
		update_time: currentTime
	}
	// 获取商品信息
	console.log("***********************华丽的分割线（获取商品信息）***********************")
	// 获取订单code集合
	let productIds = new Array();
	let productItemList = event.productItemList;
	productItemList.map(o => productIds.push(o.product_id))
	console.log("商品id集合：" + JSON.stringify(productIds));
	// 查询商品信息
	const dbCmd = db.command;
	let productList = await db.collection('product').where({
		_id: dbCmd.in(productIds)
	}).get();
	console.log("商品查询结果：" + JSON.stringify(productList))
	if(productList.data.length != productIds.length){
		return {
			success: false,
			code: -1,
			msg: '商品信息有误'
		}
	}
	
	// 构建商品信息
	let orderProductArr = productItemList.map(o => {
		let tempObj = productList.data.filter(product=>product._id == o.product_id)[0];
		let sumPrice = (parseFloat(tempObj.book_price) * parseFloat(o.num)).toFixed(2);
		orderObj.amount_payable = parseFloat(orderObj.amount_payable)+parseFloat(sumPrice);
		orderObj.real_pay = parseFloat(orderObj.real_pay)+parseFloat(sumPrice);
		return {
			order_code: orderCode, // string 订单编码
			product_id: o.product_id, // string 商品id（冗余，方便查询商品）
			num: o.num, // int 商品数量
			create_time: currentTime, // 时间戳 GMT, 创建时间
			product_code: tempObj.product_code, // string 商品编码
			product_name: tempObj.product_name, // string 商品名称
			primary_img: tempObj.primary_img, // string 商品主图
			book_price: parseFloat(tempObj.book_price), //double 商品价格
			sum_price: sumPrice, // double 商品合计价格
			sale_unit: tempObj.sale_unit, //string 销售单位
		}
	})
	console.log("构建订单商品："+JSON.stringify(orderProductArr))
	// 保存订单
	const collection = db.collection('order') // 获取表'order'的集合对象
	let res;
	res = await collection.add(orderObj);
	console.log("订单添加响应数据:" + JSON.stringify(res))
	// 保存商品
	for (var i = 0; i < orderProductArr.length; i++) {
		await db.collection('order_product').add(orderProductArr[i]);
	}
	if (!res.id) {
		return {
			success: false,
			code: -1,
			msg: '暂无数据'
		}
	}
	
	if (res.id) {
		return {
			success: true,
			code: 0,
			msg: '成功',
			data: {
				id:res.id,
				real_pay:orderObj.real_pay
			}
		}
	}
	return {
		success: false,
		code: -1,
		msg: '服务器内部错误'
	}

};
